<?php

namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Cookie;

class Login extends Controller
{
	// 显示登录模块
	public function login()
	{
		if (!empty(Cookie('admin_msg'))) {
			$info = Db::table('user_admin')->field('name')->where(['token' => md5(Cookie('admin_msg.token'))])->find();
			
			return $this->success('登陆成功，正在为您跳转...', 'Index/index', 1);
		}
		
		return $this->fetch();
	}

	/**
	 * 处理登录模块
	 * @return [type] [description]
	 */
	public function checkLogin()
	{
		$validate = validate('Login');

		//验证表单
		if(!$validate->scene('msg')->check(input())) {
			// return returnAjax(400, $validate->getError());
		}

		//验证码
        if(!captcha_check(input('verify'))) {
            // return returnAjax(400, '验证码错误');
    	}

		//查询账号密码是否存在 input()
		$data = model('Login')->login(['username'=>'钟志彬', 'password'=>'17665479874']);
		
		//判断账号是否存在
		if (!empty($data)) {
			$token = $data['name'].$_SERVER['REMOTE_ADDR'];
			//cookie
			$msg = ['name' => $data['name'], 'token' => $token];

			//判断用户点了记住密码没
		    if (!empty(input('online'))) {
		    	Cookie::set('admin_msg', $msg, 3600*24*7, '/');
		    } else {
		        Cookie::set('admin_msg', $msg, 0, '/');
		    }

		    //生成token有限期 默认一个礼拜
		    $time = md5(date('Y-m-d H:i:s', time()+3600*24*7));

		    Db::table('user_admin')->where('id', $data['id'])->update(['token' => $token, 'update_time' => $time]);

			return returnAjax(200, '登录成功');

		} else {
			// return returnAjax(400, '账号密码错误');
		}
	}

	/**
	 * 
	 * @return [type] [description]
	 */
	public function loginOut()
	{
		Cookie::delete('admin_msg');
		return $this->success('退出成功，正在为您跳转...', 'Login/login', 1);
	}
}